{
  File   : S2DLog.pas (This unit is a part of S2DE)
  S2DE   : Simple 2D Engine (software render)
  Copyright (c) 2008, Kagamma
  License: GPLv3

-----------------------------------------------------------
  Log subsystem, hien tai khong hoat dong.
}

unit S2DLog;

{$MODE DELPHI}

interface

uses
  SysUtils, Windows, S2DTypes;

procedure InitLog;
procedure AddLog(Con, AStr: String);
procedure CloseLog;

implementation

var LogFile: File of Byte;
    Info,
    Dbinfo,
    Warn,
    Error  : Word;

function LogTiming: String;
var V: DWord;
begin
  V:= GetTickCount - S2DInfo.TickStart;
  case V of
    0..9:               Result:= IntToStr(V) + '          ';
    10..99:             Result:= IntToStr(V) + '         ';
    100..999:           Result:= IntToStr(V) + '        ';
    1000..9999:         Result:= IntToStr(V) + '       ';
    10000..99999:       Result:= IntToStr(V) + '      ';
    100000..999999:     Result:= IntToStr(V) + '     ';
    1000000..9999999:   Result:= IntToStr(V) + '    ';
    10000000..99999999: Result:= IntToStr(V) + '   ';
  else
    Result := '           ';
  end;
end;

procedure AddLog(Con, AStr: String);
var tmp: String;
begin
  {$IFDEF LOG}
  tmp:= LogTiming+' '+Con+'  '+AStr+#10#13;
  BlockWrite(LogFile, tmp[1], Length(tmp)-1);
  if Con = '(i)' then Inc(Info) else
  if Con = '(w)' then Inc(Warn) else
  if Con = '(e)' then Inc(Error) else
  if Con = '(d)' then Inc(DbInfo);
  {$ENDIF}
end;

procedure InitLog;
begin
  Assign(LogFile, 'log.txt');
  ReWrite(LogFile, 1);
  S2DInfo.TickStart:= GetTickCount;
  AddLog('(I)', 'Log subsystem started');
  Info  := 0;
  Dbinfo:= 0;
  Warn  := 0;
  Error := 0;
end;

procedure CloseLog;
begin
//  AddLog('(i)', Format('Average FPS: %d', [S2DInfo.AverageFPS]));
  AddLog('(i)', Format('Max memory used: %d bytes', [S2DInfo.MaxAllocMemory]));
  if S2DInfo.TotalAllocMemory>0 then
    AddLog('(w)', Format('Amount of memory leaked: %d bytes', [S2DInfo.TotalAllocMemory]));
  AddLog('(I)', Format('Logged errors: %d, warnings: %d, infos: %d, debug info: %d', [Error, Warn, Info, DbInfo]));
  AddLog('(I)', 'Log session shutdown');
  Close(LogFile);
end;

begin

end.

